package com.example.msn_server;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;

public class MyMessengerService extends Service {

    private static final String TAG = "msn-server";

    public MyMessengerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return mMessenger.getBinder();
    }

    static class MyHander extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.i(TAG, "handleMessage, msg:" + msg);
            if (msg.replyTo != null){
                try {
                    Message reply = Message.obtain();
                    reply.what = 2;
                    reply.arg1 = msg.arg1 + msg.arg2;
                    msg.replyTo.send(reply);
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private final Messenger mMessenger = new Messenger(new MyHander());
}